package main.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import main.entity.VoteVO;
import main.service.VoteOptionService;
import main.service.VoteService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

@Controller
@RequestMapping("/vote")
public class VoteCtrl extends BaseCtrl<VoteVO> {

	@Autowired
	private VoteService voteService;
	@Autowired
	@Qualifier("voteOptionService")
	private VoteOptionService voteOptionService;
	
	@RequestMapping("/{voteID}/result.do")
//	@ResponseBody
	public String getResultByID(@PathVariable("voteID") Integer voteID, HttpServletRequest request){
		Map<String, Object> result = voteService.getResultByID(voteID);
		Gson gson = new Gson();
		request.setAttribute("result", gson.toJson(result));
		return "voteResult";
	}
	
	@RequestMapping("/{voteID}/read.do")
	public ModelAndView readByID(@PathVariable("voteID")Integer voteID){
		Map<String, Object> result = voteService.getResultByID(voteID);
		ModelAndView mdv = new ModelAndView();
		mdv.setViewName("voteDetails");
		mdv.addObject("result", result);
		return mdv;
	}
	
	@RequestMapping("/{voteID}/doVote.do")
	public String doVote(@PathVariable Integer voteID, @RequestParam Integer optionID){
		Integer uID = 0;//tempratrue method
		ModelAndView mdv = new ModelAndView();
		Boolean isOK = voteOptionService.updateByID(optionID, uID);
		if (isOK) {
			mdv.addObject("tips", "success");
		} else {
			mdv.addObject("tips", "failed");
		}
		return "redirect:/vote/"+voteID+"/read.do";
	}
	
}
